package com.shuqi.activity;

import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextUtils.TruncateAt;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.view.WindowManager.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.cc.asyncTask.AsyncTaskFailReason;
import com.cc.asyncTask.SimpleAsyncTaskListener;
import com.shuqi.activity.adapter.BookDetailsCoverListAdapter;
import com.shuqi.activity.viewport.BottomDialog;
import com.shuqi.activity.viewport.BottomToast;
import com.shuqi.activity.viewport.CommonTitle;
import com.shuqi.activity.viewport.MarqueeTextView;
import com.shuqi.activity.viewport.MyScrollView;
import com.shuqi.activity.viewport.OrderDialog;
import com.shuqi.activity.viewport.PriceChangeDialog;
import com.shuqi.activity.viewport.PriceChangeDialog.onPriceListener;
import com.shuqi.activity.viewport.ToastDialog;
import com.shuqi.application.ShuqiApplication;
import com.shuqi.common.CheckUser;
import com.shuqi.common.Constant;
import com.shuqi.common.EnterBookContent;
import com.shuqi.common.InlayBook;
import com.shuqi.common.MyTask;
import com.shuqi.common.NetErrorProvider;
import com.shuqi.common.NetNotify;
import com.shuqi.common.Urls;
import com.shuqi.common.NetErrorProvider.NetErrorListener;
import com.shuqi.common.utils.DialogUtils;
import com.shuqi.common.utils.Log4an;
import com.shuqi.common.utils.SqImageManager;
import com.shuqi.common.utils.ToastUtil;
import com.shuqi.common.utils.Util;
import com.shuqi.controller.BookCoverController;
import com.shuqi.controller.MainController;
import com.shuqi.controller.MyFavoritController;
import com.shuqi.controller.MyFavoritController.ActionEnum;
import com.shuqi.controller.R;
import com.shuqi.database.dao.impl.BookCataLogDao;
import com.shuqi.database.dao.impl.BookInfoDao;
import com.shuqi.database.dao.impl.BookMarkInfoDao;
import com.shuqi.database.model.BookCataLog;
import com.shuqi.database.model.BookInfo;
import com.shuqi.database.model.BookMarkInfo;
import com.shuqi.database.model.UserInfo;
import com.shuqi.download.database.DownloadInfo;
import com.shuqi.download.listener.DownloadStateListener;
import com.shuqi.download.util.DownloadStatus;
import com.shuqi.interfaces.CheckUserListener;
import com.shuqi.interfaces.EventTypeConstants;
import com.shuqi.interfaces.IEventListener;
import com.shuqi.model.bean.BookCoverInfo;
import com.shuqi.model.bean.BookCoverOtherBookInfo;
import com.shuqi.model.bean.BookData;
import com.shuqi.model.bean.BuyBookInfo;
import com.shuqi.model.bean.MyFavoritAddBean;
import com.shuqi.model.bean.MyFavoritRemoveBean;
import com.shuqi.model.bean.OrderInfo;
import com.shuqi.model.manager.BookCatalogManager;
import com.shuqi.model.manager.BuyBookManager;
import com.shuqi.model.manager.DownLoadBookManager;
import com.shuqi.model.manager.DownLoadShuqiBook;
import com.shuqi.model.manager.DownLoadShuqiBook.StartDownBookListener;
import com.shuqi.model.manager.MyAccountManager;
import com.shuqi.model.manager.TxtDownLoadManager;
import com.shuqi.service.ConnectionChangeReceiver;
import com.shuqi.statistics.StatisticsEventID;
import com.shuqi.statistics.StatisticsUtils;

/**
 * 书籍封面页
 * */
public class BookCoverActivity extends ActivityBase implements IEventListener, OnClickListener,
        OnItemClickListener, DownloadStateListener {
    public static final String INTENT_NAME_BOOKID = "bookId";
    private final String LogTag = "BookCover";
    private BookCoverController controller;
    private BookCoverInfo coverInfo;
    private SharedPreferences sp;
    private final int MSG_INITVIEW = 0;
    private final int MSG_DATA_OK = 1;
    private final int MSG_DATA_ERROR = 2;
    protected static final int MSG_LOAD_CATLOG = 7;// wifi下预加载目录和第一章
    private static final String TAG = "BookCoverActivity";
    /** 通知初始化按钮状态：msg.arg1 = BT_*** 、如果是下载中，并且有进度：msg.obj = 下载进度 */
    private final int MSG_INIT_BT_STATE = 3;

    private static final int MSG_MYFAVORIT_ADD_DATA_OK = 4;
    private static final int MSG_MYFAVORIT_REMOVE_DATA_OK = 5;
    private static final int MSG_MYFAVORIT_DATA_ERROR = 6;
    private static final int MSG_MYFAVORIT_NEED_LOGIN = 8;

    private String bookId;

    private LinearLayout line_404;

    private MyScrollView bookcoverScrollview;
    private CommonTitle mTitle;
    private BookData mCatalog;
    private String userId;
    private ToastDialog toastDialog;

    private TextView myFavoritAddTv;
    private TextView myFavoritRemoveTv;

    private Dialog fullDialog;

    // 收藏
    private MyFavoritController myFavoritcontroller;
    private MyFavoritRemoveBean myFavoritRemoveBean;
    private MyFavoritAddBean myFavoritAddBean;
    
    /** 跳转到登录页：请求code */
    private final int RESULTCODE_JUMPLOGIN = 100;

    /**
     * 我的收藏按钮显示比例
     * 
     */
    public enum MyFavoritButtonScaleEnum {
        _2to1, // 2:1
        _1to1, // 1:1

        ;
    }

    private int action;// 0,1添加收藏,2取消收藏

    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case MSG_INITVIEW:
                    activityLogicForward();
                    break;
                case MSG_DATA_OK:
                    activityInitData();
                    break;
                case MSG_DATA_ERROR:
                    dismissDialog();
                    line_404.setVisibility(View.VISIBLE);
                    bookcoverScrollview.setVisibility(View.GONE);
                    break;
                case MSG_INIT_BT_STATE:
                    dismissDialog();
                    updateButtonUIState(msg.arg1, msg.obj);
                    break;
                case MSG_LOAD_CATLOG:
                    loadCataData();
                    break;
                case MSG_MYFAVORIT_ADD_DATA_OK:
                    dismissDialog();
                    if (!"收藏已达到上限".equals(msg.getData().getString("message"))) {
                        myFavoritAddTv.setVisibility(View.GONE);
                        myFavoritRemoveTv.setVisibility(View.VISIBLE);

                        ToastUtil.showMessage(msg.getData().getString("message"));
                    } else {
                        showBottomFullDialog();
                    }

                    break;
                case MSG_MYFAVORIT_REMOVE_DATA_OK:
                    dismissDialog();
                    myFavoritAddTv.setVisibility(View.VISIBLE);
                    myFavoritRemoveTv.setVisibility(View.GONE);
                    ToastUtil.showMessage(msg.getData().getString("message"));
                    break;
                case MSG_MYFAVORIT_DATA_ERROR:
                    dismissDialog();
                    ToastUtil.showMessage(getString(R.string.net_error_text));
                    break;
                case MSG_MYFAVORIT_NEED_LOGIN:// 跳登陆界面
                    dismissDialog();
                    jumpLogin();
                    break;
            }
        };
    };

    /** 发送请求目录的请求 */
    private void loadCataData() {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                mCatalog =
                        BookCatalogManager.getBookCatalogByBidAndSid(bookId, "", MyAccountManager
                                .getInstance(BookCoverActivity.this).getUserId(),
                                BookMarkInfo.TYPE_NEW_PAY_BOOKMARK);

                Log4an.i(TAG, "获取第一章的目录");
                BookCataLog cata;
                // 获取第一章的目录
                if(mCatalog!=null){
                    cata = mCatalog.getInfos().get(1);
                    setTempBookIdAndUserId(cata);
                }else{
                    cata =null;
                }
                
                if (cata != null) {
                    Log4an.i(TAG, "cata.getChapterId():" + cata.getChapterId() + "----"
                            + "cata.getUserId():" + cata.getUserId() + "----"
                            + "cata.getChapterName():" + cata.getChapterName() + "---"
                            + "cata.getSourceId():" + cata.getSourceId());

                    List<String> chapterContent =
                            DownLoadBookManager.loadPayChapterContent(
                                    ShuqiApplication.getContext(), cata.getChapterContentUrl());
                    if (chapterContent != null && chapterContent.size() > 0) {
                        chapterInfo = chapterContent.get(0);
                    }
                    
                    if (chapterContent != null && !"".equals(chapterContent)) {

                        DownLoadBookManager.writeChapterFile(null, bookId, cata.getUserId(), cata.getChapterId(), chapterInfo);
//                        Log4an.i(TAG, "cata.getChapterId():" + cata.getChapterId() + "----"
//                                + "cata.getUserId():" + cata.getUserId() + "----"
//                                + "cata.getChapterName():" + cata.getChapterName() + "---"
//                                + "cata.getSourceId():" + cata.getSourceId()+"+++++++++"+chapterInfo);
                        // 更新数据库下载状态
                        BookCataLogDao.getInstance().updateCatalogToDown(bookId, null, cata.getUserId(), cata.getChapterId());
                        Log4an.i(TAG, "-------------------------------2");
                        int count = (int) BookCataLogDao.getInstance().getChapterDownLoadCount(cata.getUserId(), bookId);
                        // 更新书籍信息--总下载章节数量
                        if (count > 0) {
                            Log4an.i(TAG, "-------------------------------3");
                            BookInfo bookInfo = new BookInfo();
                            bookInfo.setSourceId(cata.getSourceId());
                            bookInfo.setBookId(bookId);
                            bookInfo.setUserId(cata.getUserId());
                            bookInfo.setBookDownCount(count);
                            BookInfoDao.getInstance().saveOrUpdateBookInfo(bookInfo);
                        }
                    }
                    // String content=DownLoadBookManager.downChapter(BookCoverActivity.this,
                    // cata.getSourceId(), bookId,
                    // cata.getChapterId(), cata.getUserId());
//                     Log4an.i(TAG, "根据第一章目录获取第一章的内容"+chapterInfo);

                }
            }

            private void setTempBookIdAndUserId(BookCataLog cata) {
                sp = getSharedPreferences("tempcatalog", MODE_PRIVATE);
                Editor editor = sp.edit();
                userId = MyAccountManager.getInstance(getApplicationContext(), true).getUserId();
                String[] bids=InlayBook.getInlayBooks();
                for (int i = 0; i < bids.length; i++) {
                    if(bids[i].equals(cata.getBookId())){
                         return;
                    }
                }
                editor.putString(cata.getBookId()+"##"+userId+"##"+cata.getSourceId(), cata.getChapterId());
                editor.commit();
            }
        };
        MyTask.runInBackground(runnable, true);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.act_bookcover);

        controller =
                (BookCoverController) MainController.getMainManagerInstance().createController(
                        MainController.CONTROLLER_ID_BOOKCOVER, this);
        controller.addEventListener(this);


        // 收藏控制器
        myFavoritcontroller =
                (MyFavoritController) MainController.getMainManagerInstance().createController(
                        MainController.CONTROLLER_ID_MY_FAVORIT, this);
        myFavoritcontroller.addEventListener(this);


        bookId = getIntent().getStringExtra(INTENT_NAME_BOOKID);
        if("open".equals(getIntent().getStringExtra("push_book"))){
            StatisticsUtils.onEvent(this,StatisticsEventID.PUSHMESSAGE_BOOK_OPEN);
        }
        
        super.onCreate(savedInstanceState);
        bookcoverScrollview = (MyScrollView) findViewById(R.id.bookcover_scrollview);
        line_404 = (LinearLayout) findViewById(R.id.include_error);
        findViewById(R.id.retry).setOnClickListener(this);
        mTitle = (CommonTitle) findViewById(R.id.title);
        mTitle.setImageListener(this);
        handler.sendEmptyMessage(MSG_INITVIEW); // 通知初始化View
        loadDate(); // 通知加载数据
    }

    /** 刷新封面数据数据 */
    private void loadDate() {
        if (controller != null) {
            userId = MyAccountManager.getInstance(getApplicationContext(), true).getUserId();
            controller.handle(0, bookId, userId);
            action = 0;
        }

    }

    /**
     * 如果进入详情后是wifi则预加载目录和第一章的内容
     */
    private void preLoadCatalogAndFirstContent() {
        int mNetType = ConnectionChangeReceiver.getNetType(ShuqiApplication.getContext());
        if (mNetType == ConnectionChangeReceiver.NET_TYPE_WIFI) {
            loadCataData();
        }
    }

    /** 价格变动，确认购买完成之后通知更新 */
    public void loadCoverData(String s) {
        Message message = new Message();
        message.what = MSG_INIT_BT_STATE;
        message.arg1 = BT_BUY_BOOK_SUCCES;
        message.obj = s;
        handler.sendMessage(message);
    }

    @Override
    public void onEvent(int event, Object data) {

        switch (event) {
            case EventTypeConstants.EVENT_SUCCESS:// 读取数据 写处理逻辑

                if (data instanceof BookCoverInfo) {

                    coverInfo = (BookCoverInfo) data;
                    handler.sendEmptyMessage(MSG_DATA_OK);
                    saveBookInfo(coverInfo);

                } else if (data instanceof MyFavoritRemoveBean) {// 删除收藏

                    myFavoritRemoveBean = (MyFavoritRemoveBean) data;
                    
                    if ("304".equals(myFavoritRemoveBean.getState())) {// 需要登陆
                        Message msg = Message.obtain();
                        msg.what = MSG_MYFAVORIT_NEED_LOGIN;
                        Bundle bundle = new Bundle();
                        bundle.putString("message", myFavoritRemoveBean.getMessage());
                        msg.setData(bundle);
                        handler.sendMessage(msg);
                        return;
                    }

                    Message msg = Message.obtain();
                    msg.what = MSG_MYFAVORIT_REMOVE_DATA_OK;
                    Bundle bundle = new Bundle();
                    bundle.putString("message", myFavoritRemoveBean.getMessage());
                    msg.setData(bundle);

                    handler.sendMessage(msg);

                } else if (data instanceof MyFavoritAddBean) {// 添加收藏

                    myFavoritAddBean = (MyFavoritAddBean) data;
                    
                    if ("304".equals(myFavoritAddBean.getState())) {// 需要登陆
                        Message msg = Message.obtain();
                        msg.what = MSG_MYFAVORIT_NEED_LOGIN;
                        Bundle bundle = new Bundle();
                        bundle.putString("message", myFavoritAddBean.getMessage());
                        msg.setData(bundle);
                        handler.sendMessage(msg);
                        return;
                    }

                    Message msg = Message.obtain();
                    msg.what = MSG_MYFAVORIT_ADD_DATA_OK;
                    Bundle bundle = new Bundle();
                    bundle.putString("message", myFavoritAddBean.getMessage());
                    msg.setData(bundle);

                    handler.sendMessage(msg);

                }

                break;

            case MSG_LOAD_CATLOG:

                break;
            default:
                if (action == 0)
                    handler.sendEmptyMessage(MSG_DATA_ERROR);
                else if (action == 1)
                    handler.sendEmptyMessage(MSG_MYFAVORIT_DATA_ERROR);
                else if (action == 2)
                    handler.sendEmptyMessage(MSG_MYFAVORIT_DATA_ERROR);

                break;



        }
    }

    /**
     * 保存书籍信息
     */
    private void saveBookInfo(BookCoverInfo coverInfo) {
        if (coverInfo != null) {
            String userId = MyAccountManager.getInstance(this).getUserId();
            BookInfo info = new BookInfo();
            info.setUserId(userId);
            info.setBookAuthorName(coverInfo.getAuthor());
            info.setBookId(coverInfo.getBookId());
            info.setBookName(coverInfo.getBookName());
            info.setBookType(coverInfo.getBookType());
            info.setBookCoverImgUrl(coverInfo.getImageUrl());
            info.setBookUpdateTime(System.currentTimeMillis());
            info.setBookIntro(coverInfo.getDescription());
            if (coverInfo.getPaid() != null) {
                info.setBookPayState(Integer.valueOf(coverInfo.getPaid()));
            }

            try {
                if (!TextUtils.isEmpty(coverInfo.getPrice())) {
                    info.setBookPrice(Float.valueOf(coverInfo.getPrice()));
                }
            } catch (Exception e) {
            }
            if (coverInfo.getBookState() != null) {
                info.setBookStatus(coverInfo.getBookState());
            }

            info.setSourceType(BookInfo.SOURCE_TYPE_SHUQI);
            info.setBookHistoryState(1);// 需要加入到浏览历史里

            try {
                BookInfo bookinfo = BookInfoDao.getInstance().getBookInfo("", bookId, userId);
                // 书籍付费模式有变动，不保存付费模式，等待目录联网更新后由目录来更新付费模式
                if (bookinfo == null) {
                    info.setBookPayMode(coverInfo.getPayMode());
                    Log4an.i(LogTag, "first save bookCoverInfo payMode=" + coverInfo.getPayMode());
                } else {
                    info.setUpdateCatalog(bookinfo.getUpdateCatalog());
                    Log4an.e(LogTag, "bookcatalog isNeedupdate "
                            + (bookinfo.getUpdateCatalog() == BookInfo.UPDATE_CATALOG_YES));
                    Log4an.e(
                            LogTag,
                            "update local bookCoverInfo but payMode: local="
                                    + bookinfo.getBookPayMode() + " new=" + coverInfo.getPayMode());
                }
                BookInfoDao.getInstance().saveOrUpdateBookInfo(info);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void activityLogicForward() {
        myFavoritAddTv = (TextView) findViewById(R.id.bookcover_bt_my_favority_add);
        myFavoritRemoveTv = (TextView) findViewById(R.id.bookcover_bt_my_favority_remove);

        // 数据加载之前的View操作
        StatisticsUtils.onEvent(this, StatisticsEventID.BOOKCOVER_BOOKCOVER);
        showLoading(true);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_left:
                ActivityManager.getInstance().finishActivity(this);
                break;
            case R.id.title_right:
                BookShelfActivity.show(this, true);
                StatisticsUtils.onEvent(this, StatisticsEventID.BOOKCOVER_BOOKSHELF);
                break;
            case R.id.bookcover_tv_chapter_more:
                Intent intent2 = new Intent(BookCoverActivity.this, BookCatalogActivity.class);
                intent2.putExtra(INTENT_NAME_BOOKID, bookId);
                ActivityManager.getInstance().startActivity(intent2, this);
                StatisticsUtils.onEvent(this, StatisticsEventID.BOOKCOVER_SEEALL_CAP);
                break;
            case R.id.bookcover_tv_author:
                StatisticsUtils.onEvent(BookCoverActivity.this,
                        StatisticsEventID.BOOKCOVER_BOOKCOVER_AUTHOR);
                if (!TextUtils.isEmpty(coverInfo.getAuthorId())) {
                    WebCommonActivity.openWebCommonForAvoidCycle(this, coverInfo.getAuthor(), Urls.getWebShuqiAuthorBooksUrl(this, coverInfo.getAuthorId()));
                }
                break;
            case R.id.bookcover_tv_type:
                StatisticsUtils.onEvent(BookCoverActivity.this,
                        StatisticsEventID.BOOKCOVER_BOOK_KIND);
                if (!TextUtils.isEmpty(coverInfo.getBookTypeId())) {
                    WebCommonActivity.openWebCommonForAvoidCycle(this, coverInfo.getBookType(), 
                            Urls.getWebShuqiCategoryBooksUrl(this, coverInfo.getBookTypeId()));
                }
                break;
            case R.id.retry:
             // 重试动画组件
                NetErrorProvider.getInstance().retry(this, new NetErrorListener() {
                    @Override
                    public void netErrorCallback() {
                        showLoading(true);
                        loadDate(); // 通知加载数据
                    }
                });
                
                break;
            case R.id.dialog_cancel_tv:
                hideNetWorkDialog();
                break;
            case R.id.dialog_confirm_tv:
                hideNetWorkDialog();
                NetNotify.getInstance().changeNotifyState(NetNotify.DOWNLOAD_BOOK_READ);
                onStartDownBook();
                break;
            case R.id.bookcover_newchapter:
                StatisticsUtils.onEvent(this, StatisticsEventID.BOOKCOVER_NEW_CAP);
                onStartReadNewChapter();
                break;
        }
    }

    /** 购买对象 */
    private BuyBookInfo buyBookInfo = null;

    /** 购买全本方法，成功后 更新：试读、下载两个 按钮状态：在弹出对话框点击购买按钮后调用 */
    public void mBuyBookOnline() {
        if (!Util.isNetworkConnected(BookCoverActivity.this)) {
            final Message msg = new Message();
            msg.what = MSG_INIT_BT_STATE;
            msg.arg1 = BT_BUYALLBOOK_FAILURE;
            msg.obj = getString(R.string.retry_after_connect_network);
            handler.sendMessage(msg);
            return;
        }

        final Message msg = new Message();
        msg.what = MSG_INIT_BT_STATE;

        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    String price =
                            TextUtils.isEmpty(coverInfo.getDiscount()) ? coverInfo.getOldPrice()
                                    : coverInfo.getPrice();
                    buyBookInfo =
                            BuyBookManager.buyBookOnline(BookCoverActivity.this, coverInfo
                                    .getBookId(), coverInfo.getFirstChapterId(), MyAccountManager
                                    .getInstance(BookCoverActivity.this).getUserId(), price); // 打开即为请求购买全本
                                                                                              // coverInfo.getPrice()
                    if (buyBookInfo != null && "1".equals(buyBookInfo.getType())) {
                        msg.arg1 = BT_BUYALLBOOK_SUCCES;
                    } else if (buyBookInfo != null && "10".equals(buyBookInfo.getType())) {
                        msg.arg1 = BT_AUTHENTICATION_FAILED;
                        msg.obj = buyBookInfo.getInfo();
                    } else if (buyBookInfo != null && "13".equals(buyBookInfo.getType())) {// 新加价格变动
                        runOnUiThread(new Runnable() {
                            public void run() {
                                PriceChangeDialog mPriceChangeDialog =
                                        new PriceChangeDialog(BookCoverActivity.this, orderInfo,
                                                new onPriceListener() {

                                                    @Override
                                                    public String getOldPrice() {
                                                        return orderInfo.getPrice();
                                                    }

                                                    @Override
                                                    public String getNewPrice() {
                                                        return buyBookInfo.getCurChapterPrice();
                                                    }
                                                });
                                mPriceChangeDialog.show();
                                if (orderdialog != null && orderdialog.isShowing()) {
                                    orderdialog.dismiss();
                                }
                                StatisticsUtils.onEvent(BookCoverActivity.this,
                                        StatisticsEventID.BOOKCONTENT_PRICE_CHANGE);
                            }
                        });
                        return;
                    } else {
                        msg.arg1 = BT_BUYALLBOOK_FAILURE;
                        if (buyBookInfo != null) {
                            msg.obj = buyBookInfo.getInfo();
                        }
                    }
                    handler.sendMessage(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                    if (orderdialog != null) {
                        orderdialog.dismiss();
                    }
                    return;
                }

            }
        }).start();
    }

    private void showLoading(boolean isShow) {
        bookcoverScrollview.setVisibility(isShow ? View.GONE : View.VISIBLE);
        line_404.setVisibility(View.GONE);
        findViewById(R.id.include_loading).setVisibility(isShow ? View.VISIBLE : View.GONE);
    }

    @Override
    public void activityInitData() {
        if (coverInfo != null) {
            if (coverInfo.isHide()) {
                showMsg(getString(R.string.error_bookswitch_ishide));
                ActivityManager.getInstance().finishActivity(this);
                return;
            } else if (!coverInfo.isCoverOpen()) {
                showMsg(getString(R.string.error_bookswitch_coverisclose));
                ActivityManager.getInstance().finishActivity(this);
                return;
            }

            if ("1".equals(coverInfo.getCollected())) {// 已收藏
                myFavoritAddTv.setVisibility(View.GONE);
                myFavoritRemoveTv.setVisibility(View.VISIBLE);
                myFavoritRemoveTv.setClickable(true);
            } else {
                myFavoritAddTv.setVisibility(View.VISIBLE);
                myFavoritRemoveTv.setVisibility(View.GONE);
                myFavoritRemoveTv.setClickable(false);
            }



            ImageView iv_cover = (ImageView) findViewById(R.id.bookcover_iv_cover);
            asyncLoadImg(iv_cover);

            ImageView iv_state = (ImageView) findViewById(R.id.bookcover_iv_state);
            if ("1".equals(coverInfo.getBookState())) {
                iv_state.setImageResource(R.drawable.icon_bookcover_bookstate_keep);
            } else if ("2".equals(coverInfo.getBookState())) {
                iv_state.setImageResource(R.drawable.icon_bookcover_bookstate_end);
            } else {
                iv_state.setVisibility(View.GONE);
            }

            ((TextView) findViewById(R.id.bookcover_tv_name)).setText(coverInfo.getBookName());
            ((TextView) findViewById(R.id.bookcover_tv_author)).setText(Html
                    .fromHtml("作者：<font color=#14be7b>"
                            + (coverInfo.getAuthor() == null ? "" : coverInfo.getAuthor())
                            + "</font>"));
            ((TextView) findViewById(R.id.bookcover_tv_type)).setText(Html
                    .fromHtml("类型：<font color=#14be7b>"
                            + (coverInfo.getBookType() == null ? "" : coverInfo.getBookType())
                            + "</font>"));
            if (!TextUtils.isEmpty(coverInfo.getAuthorId())) {
                findViewById(R.id.bookcover_tv_author).setOnClickListener(this);
            }
            if (!TextUtils.isEmpty(coverInfo.getBookTypeId())) {
                findViewById(R.id.bookcover_tv_type).setOnClickListener(this);
            }
            ((TextView) findViewById(R.id.bookcover_tv_words)).setText("字数："
                    + (coverInfo.getBookWords() == null ? "" : coverInfo.getBookWords()) + "字");

            // 限免、按章收费、整本收费、整本免费
            int color_yellow = 0xfffa9b1f;
            TextView tv_price = (TextView) findViewById(R.id.bookcover_tv_price);
            TextView tv_oldPrice = (TextView) findViewById(R.id.bookcover_tv_oldprice);
            TextView tv_discounts = (TextView) findViewById(R.id.bookcover_tv_discounts);
            switch (coverInfo.getPayMode()) {
                case Constant.PAYMODE_BOOK_FREE:// 全本免费（相当于购买完成的正本后状态）
                case Constant.PAYMODE_FREE:// 限时免费
                    tv_oldPrice.setTextColor(color_yellow);
                    tv_oldPrice.setText("限时免费");
                    tv_price.setVisibility(View.GONE);
                    tv_discounts.setVisibility(View.GONE);
                    break;
                case Constant.PAYMODE_BOOK:// 整本收费
                    if ("1".equals(coverInfo.getPaid())) {
                        tv_oldPrice.setText("已购买");
                        tv_oldPrice.setTextColor(color_yellow);
                        tv_price.setVisibility(View.GONE);
                        tv_discounts.setVisibility(View.GONE);
                    } else if (TextUtils.isEmpty(coverInfo.getDiscount())) {
                        tv_oldPrice.setText(coverInfo.getOldPrice() + "书豆/本");
                        tv_oldPrice.setTextColor(color_yellow);
                        tv_price.setVisibility(View.GONE);
                        tv_discounts.setVisibility(View.GONE);
                    } else {
                        tv_price.setText(coverInfo.getPrice() + "书豆/本");
                        tv_oldPrice.setText(coverInfo.getOldPrice() + "书豆/本");
                        tv_oldPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                        tv_discounts.setText(coverInfo.getDiscount() + "折");
                    }
                    break;
                case Constant.PAYMODE_CHAPTER:// 按章收费
                    if (TextUtils.isEmpty(coverInfo.getDiscount())) {
                        tv_oldPrice.setText(coverInfo.getPrice() + "书豆/千字");
                        tv_oldPrice.setTextColor(color_yellow);
                        tv_price.setVisibility(View.GONE);
                        tv_discounts.setVisibility(View.GONE);
                    } else {
                        tv_price.setText(coverInfo.getPrice() + "书豆/千字");
                        tv_oldPrice.setText(coverInfo.getOldPrice() + "书豆/千字");
                        tv_oldPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                        tv_discounts.setText(coverInfo.getDiscount() + "折");
                    }
                    break;
            }

            // 简介
            final TextView description = (TextView) findViewById(R.id.bookcover_tv_des);
            final ImageView status = (ImageView) findViewById(R.id.bookcover_tv_des_more);
            String bookdescription = coverInfo.getDescription();
            if (TextUtils.isEmpty(bookdescription)) {
                bookdescription = "暂无简介...";
                status.setVisibility(View.GONE);
            } else {
                if(bookdescription.length()>152){
                    bookdescription = bookdescription.substring(0, 150)+"...";
                    coverInfo.setDescription(bookdescription);
                }
                description.getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener() {
                    @Override
                    public boolean onPreDraw() {
                        if (description.getLineCount() <= 3 && description.getLineCount() != 0) {
                            findViewById(R.id.bookcover_tv_des_more).setVisibility(View.GONE);
                        } else {
                            description.setMaxLines(3);
                            findViewById(R.id.bookcover_tv_des_more).setVisibility(View.VISIBLE);
                        }
                        try {
                            description.getViewTreeObserver().removeOnPreDrawListener(this);
                        } catch (Exception e) {
                        }
                        return true;
                    }
                });
                description.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        StatisticsUtils.onEvent(BookCoverActivity.this,
                                StatisticsEventID.BOOKCOVER_READ_BOOKDESC);
                        description.setMaxLines(Integer.MAX_VALUE);
                        description.setText(coverInfo.getDescription());
                        status.setVisibility(View.GONE);
                    }
                });
                status.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        StatisticsUtils.onEvent(BookCoverActivity.this,
                                StatisticsEventID.BOOKCOVER_READ_BOOKDESC);
                        description.setMaxLines(Integer.MAX_VALUE);
                        description.setText(coverInfo.getDescription());
                        status.setVisibility(View.GONE);
                    }
                });
            }
            description.setText(bookdescription);

            // 关键字
            LinearLayout keywords = (LinearLayout) findViewById(R.id.bookcover_ll_tags);
            keywords.removeAllViews();
            int width = Util.getScreenWidth();
            int btnWidth = (width - Util.dip2px(this, 18) * 2 - Util.dip2px(this, 8) * 3) / 4;

            if (coverInfo.getTagList() != null && coverInfo.getTagList().size() > 0) {
                DisplayMetrics dm = new DisplayMetrics();
                getWindowManager().getDefaultDisplay().getMetrics(dm);
                for (int i = 0; i < coverInfo.getTagList().size() && i < 4; i++) {
                    MarqueeTextView btn = new MarqueeTextView(this);
                    int resourceId = R.drawable.btn_bookcover_tag_violet; 
                    if(i==0){
                        resourceId = R.drawable.btn_bookcover_tag_violet;
                    }else if(i==1){
                        resourceId = R.drawable.btn_bookcover_tag_cyan;
                    }else if(i==2){
                        resourceId = R.drawable.btn_bookcover_tag_blue;
                    }else if(i==3){
                        resourceId = R.drawable.btn_bookcover_tag_orange;
                    }
                    btn.setBackgroundResource(resourceId);
                    
                    btn.setGravity(Gravity.CENTER);
                    btn.setText(coverInfo.getTagList().get(i).getName());
                    btn.setTextAppearance(this, R.style.TextColorWhite2Black);
                    btn.setTextSize(13.32f);
                    btn.setSingleLine(true);
                    btn.setClickable(true);
                    btn.setEllipsize(TruncateAt.END);
                    final String keywordId = coverInfo.getTagList().get(i).getId();
                    final String keywordName = coverInfo.getTagList().get(i).getName();
                    btn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            StatisticsUtils.onEvent(BookCoverActivity.this,
                                    StatisticsEventID.BOOKCOVER_LABEL);
                            WebCommonActivity.openWebCommonForAvoidCycle(BookCoverActivity.this, keywordName,
                                    Urls.getWebShuqiTagBooksUrl(BookCoverActivity.this, keywordName));
                        }
                    });
                    LinearLayout.LayoutParams params =
                            new LinearLayout.LayoutParams(btnWidth, Util.dip2px(this, 36));
                    if (i == 0) {
                        params.leftMargin = Util.dip2px(this, 18);
                    } else {
                        params.leftMargin = Util.dip2px(this, 8);
                    }
                    keywords.addView(btn, params);
                }
            } else {
                ((View) findViewById(R.id.the_second_line)).setVisibility(View.GONE);
                ((TextView) findViewById(R.id.bookcover_tags_show)).setVisibility(View.GONE);
                keywords.setVisibility(View.GONE);
            }

            // 最新章节
            if (coverInfo.getNewChapter() != null && !TextUtils.isEmpty(coverInfo.getNewChapter().getChapterID())) {
                ((TextView) findViewById(R.id.bookcover_tv_chapter_name)).setText(coverInfo
                        .getNewChapter().getChapterName());
                ((TextView) findViewById(R.id.bookcover_tv_chapter_time)).setText(coverInfo
                        .getNewChapter().getUpdateTime());
                findViewById(R.id.bookcover_newchapter).setOnClickListener(this);
                findViewById(R.id.bookcover_newchapter_ll).setOnClickListener(this);
                findViewById(R.id.bookcover_tv_chapter_more).setOnClickListener(this);
            } else {
                findViewById(R.id.bookcover_newchapter_ll).setVisibility(View.GONE);
            }
            //
            ListView listView = (ListView) findViewById(R.id.bookcover_lv_otherbook);
            if (coverInfo.getOtherList() != null && coverInfo.getOtherList().size() > 0) {
                BookDetailsCoverListAdapter adapter =
                        new BookDetailsCoverListAdapter(this, coverInfo.getOtherList());
                int totalHeight = (Util.dip2px(this, 118) + 2) * adapter.getCount() - 2;
                ViewGroup.LayoutParams params = listView.getLayoutParams();
                params.height = totalHeight;
                listView.setLayoutParams(params);
                listView.setAdapter(adapter);
                listView.setOnItemClickListener(this);
            } else {
                ((View) findViewById(R.id.the_third_line)).setVisibility(View.GONE);
                ((TextView) findViewById(R.id.bookcover_other_show)).setVisibility(View.GONE);
                listView.setVisibility(View.GONE);
            }

            // findViewById(R.id.bookcover_bt_read_pay).setVisibility(View.VISIBLE);
            // findViewById(R.id.bookcover_bt_read_free).setVisibility(View.VISIBLE);

            // 初始化购买按钮状态
            initButtonState(coverInfo);
            // 注册下载监听事件
            // FreeBookDownloadManager.getInstance().registerDownStateListener(this);
            DownLoadShuqiBook.getInstace().registerDownStateListener(this);
            // 添加统计
            if (coverInfo.getPayMode() == Constant.PAYMODE_FREE) {
                StatisticsUtils.onEvent(StatisticsEventID.BOOKCOVER_TIME_FREE_BOOKCOVER);
            } else if (coverInfo.getPayMode() == Constant.PAYMODE_BOOK) {
                StatisticsUtils.onEvent(StatisticsEventID.BOOKCOVER_INTO_ALLBOOK_BUY);
            } else if (coverInfo.getPayMode() == Constant.PAYMODE_CHAPTER) {
                StatisticsUtils.onEvent(StatisticsEventID.BOOKCOVER_INTOCAPTET_BUY);
            }
        }
        showLoading(false);
        // DownChapterManager.registerDownBookInterface(this, this);
    }

    /** 更新：试读、下载两个 按钮状态： */
    private void initButtonState(BookCoverInfo coverinfo) {
        Message msg = new Message();
        msg.what = MSG_INIT_BT_STATE;
        if ("1".equals(coverinfo.getPaid())) {
            msg.arg1 = BT_HAD_BUY_ALLBOOK_SUCCES;
        } else {
            switch (coverinfo.getPayMode()) {
                case 0: // 限时免费
                    msg.arg1 = BT_TIME_LIMITFREE;
                    break;
                case 1:// 全本收费 若果购买成功 变为一个下载按钮
                    msg.arg1 = BT_FREE_OR_BUY;
                    break;
                case 2:// 按章收费 免费试读按钮
                    msg.arg1 = BT_FREETRYREAD;
                    break;
                case 3:// 全本免费 （下载按钮） 如果已经下载过 变为阅读按钮
                    msg.arg1 = BT_DOWN;
                    break;
            }
        }
        handler.sendMessage(msg);
    }

    /** 限时免费书籍 下载全本按钮 下载完成变为阅读按钮 */
    private final int BT_TIME_LIMITFREE = -99;
    /** 免费试读 + 购买全本 */
    private final int BT_FREE_OR_BUY = -100;
    /** 下载全本 */
    private final int BT_DOWN = -101;
    /** 等待下载 */
    private final int BT_DOWN_WAITING = -102;
    /** 下载中...不可阅读 */
    private final int BT_DOWNING = -103;
    /** 下载中...可阅读（即下载完成） */
    private final int BT_DOWANING_CANREAD = -107;
    /** 下载失败，点击重新下载 */
    private final int BT_DOWN_ERROR = -104;

    /** 停止解压 即下载失败 */
    private final int BT_UNZIP_STOP = -115;
    /** 正在解压 */
    private final int BT_STATE_UNZIP = -116;
    /** 网络连接失败 */
    private final int BT_STATE_CONNECTERROR = -117;


    /** 阅读 */
    private final int BT_READ = -105;
    /** 免费试读 */
    private final int BT_FREETRYREAD = -106;
    /** 购买正本成功后 */
    private final int BT_BUYALLBOOK_SUCCES = -108;
    /** 购买整本失败后 */
    private final int BT_BUYALLBOOK_FAILURE = -109;
    /** 已经购买过 */
    private final int BT_HAD_BUY_ALLBOOK_SUCCES = -110;
    /** 身份验证失败 */
    private final int BT_AUTHENTICATION_FAILED = -111;
    /** 价格变动购买成功 */
    private final int BT_BUY_BOOK_SUCCES = -112;// 仅保证运行稳定加此参数,应与-108整合

    /** 更新按钮UI状态和点击事件 */
    private void updateButtonUIState(int state, Object per) {
        TextView btFree = ((TextView) findViewById(R.id.bookcover_bt_read_free));
        TextView btPay = ((TextView) findViewById(R.id.bookcover_bt_read_pay));
        switch (state) {
            case BT_TIME_LIMITFREE: {

                updateButton(MyFavoritButtonScaleEnum._2to1);// 更新收藏按钮显示大小，显示比例2：1

                btPay.setVisibility(View.GONE);
                btPay.setClickable(false);
                btFree.setVisibility(View.VISIBLE);

                btFree.setText("阅读");
                btFree.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        StatisticsUtils.onEvent(BookCoverActivity.this,
                                StatisticsEventID.BOOKCOVER_TIME_BOOKCOVER_READ);
                        onStartReadBook(false);
                    }
                });

                break;
            }
            case BT_FREE_OR_BUY:

                updateButton(MyFavoritButtonScaleEnum._1to1);// 更新收藏按钮显示大小，显示比例1：1

                btFree.setVisibility(View.VISIBLE);
                btFree.setClickable(true);
                btFree.setText("免费试读");
                btFree.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        StatisticsUtils.onEvent(BookCoverActivity.this,
                                StatisticsEventID.BOOKCOVER_TRY_READ);
                        onStartReadBook(false);
                    }
                });
                btPay.setVisibility(View.VISIBLE);
                btPay.setText("购买全本");
                btPay.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        StatisticsUtils.onEvent(BookCoverActivity.this,
                                StatisticsEventID.BOOKCOVER_ALLBOOK_BUY);
                        onStartBuyBook();
                    }
                });

                break;
            case BT_DOWN: {

                updateButton(MyFavoritButtonScaleEnum._2to1);// 更新收藏按钮显示大小，显示比例2：1

                btPay.setVisibility(View.GONE);
                btPay.setClickable(false);
                btFree.setVisibility(View.VISIBLE);

                DownloadInfo downInfo =
                        DownLoadShuqiBook.getInstace().getDownBookState(
                                MyAccountManager.getInstance(this).getUserId(), bookId); // 获取下载信息
                if (downInfo != null) {
                    mShowDownLoadStates(downInfo, btFree);
                } else {
                    btFree.setText("下载全本");
                    btFree.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            StatisticsUtils.onEvent(BookCoverActivity.this,
                                    StatisticsEventID.BOOKCOVER_DOWNLOAD_ALLBOOK);
                            onStartDownBook();
                        }
                    });
                }

                break;
            }
            case BT_DOWN_WAITING:

                updateButton(MyFavoritButtonScaleEnum._2to1);// 更新收藏按钮显示大小，显示比例2：1

                btPay.setVisibility(View.GONE);
                btPay.setClickable(false);
                btFree.setVisibility(View.VISIBLE);
                btFree.setText("等待下载...");
                btFree.setClickable(false);
                break;
            case BT_DOWNING:

                updateButton(MyFavoritButtonScaleEnum._2to1);// 更新收藏按钮显示大小，显示比例2：1

                btPay.setVisibility(View.GONE);
                btPay.setClickable(false);
                btFree.setVisibility(View.VISIBLE);
                if (per != null) {
                    String perLoading = (String) per;
                    btFree.setText(perLoading + "%  下载中...");
                    Log.e("mine", "收到的进度：" + perLoading);
                }
                btFree.setClickable(false);
                break;
            case BT_DOWANING_CANREAD:

                updateButton(MyFavoritButtonScaleEnum._2to1);;// 更新收藏按钮显示大小，显示比例2：1

                btPay.setVisibility(View.GONE);
                btPay.setClickable(false);
                btFree.setVisibility(View.VISIBLE);
                btFree.setText("阅读");
                btFree.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        onStartReadBook(true);
                    }
                });
                break;
            case BT_DOWN_ERROR:

                updateButton(MyFavoritButtonScaleEnum._2to1);// 更新收藏按钮显示大小，显示比例2：1

                btPay.setVisibility(View.GONE);
                btPay.setClickable(false);
                btFree.setVisibility(View.VISIBLE);
                if (per != null) {
                    String perLoading = (String) per;
                    btFree.setText(perLoading + "%  继续下载");
                }
                btFree.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        onStartDownBook();
                    }
                });
                // showMsg("下载异常，请重试");
                break;
            case BT_STATE_CONNECTERROR: { // 网络连接失败

                updateButton(MyFavoritButtonScaleEnum._2to1);// 更新收藏按钮显示大小，显示比例2：1

                btPay.setVisibility(View.GONE);
                btPay.setClickable(false);
                DownloadInfo downInfo =
                        DownLoadShuqiBook.getInstace().getDownBookState(
                                MyAccountManager.getInstance(this).getUserId(), bookId); // 获取下载信息
                if (downInfo != null) {
                    mShowDownLoadStates(downInfo, btFree);
                } else {
                    btFree.setVisibility(View.VISIBLE);
                    btFree.setText("继续下载");
                    btFree.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            onStartDownBook();
                        }
                    });
                }
                break;
            }
            case BT_READ:

                updateButton(MyFavoritButtonScaleEnum._2to1);// 更新收藏按钮显示大小，显示比例2：1

                btPay.setVisibility(View.GONE);
                btPay.setClickable(false);
                btFree.setVisibility(View.VISIBLE);
                btFree.setText("阅读");
                btFree.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        onStartReadBook(true);
                    }
                });
                break;
            case BT_FREETRYREAD:

                updateButton(MyFavoritButtonScaleEnum._2to1);// 更新收藏按钮显示大小，显示比例2：1

                btFree.setVisibility(View.VISIBLE);
                btFree.setClickable(true);
                btFree.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        StatisticsUtils.onEvent(BookCoverActivity.this,
                                StatisticsEventID.BOOKCOVER_FREE_TRYREAD);
                        onStartReadBook(false);
                    }
                });
                btPay.setVisibility(View.GONE);
                btPay.setClickable(false);

                break;
            case BT_HAD_BUY_ALLBOOK_SUCCES:

                updateButton(MyFavoritButtonScaleEnum._2to1);// 更新收藏按钮显示大小，显示比例2：1

                ((TextView) findViewById(R.id.bookcover_tv_price)).setText("已购买");
                ((TextView) findViewById(R.id.bookcover_tv_price)).setTextColor(Color
                        .parseColor("#ffaf10"));
                ((TextView) findViewById(R.id.bookcover_tv_price)).setVisibility(View.VISIBLE);
                ((TextView) findViewById(R.id.bookcover_tv_oldprice)).setVisibility(View.GONE);
                ((TextView) findViewById(R.id.bookcover_tv_discounts)).setVisibility(View.GONE);
                btPay.setVisibility(View.GONE);
                btPay.setClickable(false);
                btFree.setVisibility(View.VISIBLE);

                DownloadInfo downInfo =
                        DownLoadShuqiBook.getInstace().getDownBookState(
                                MyAccountManager.getInstance(this).getUserId(), bookId); // 获取下载信息
                if (downInfo != null) {
                    mShowDownLoadStates(downInfo, btFree);
                } else {
                    btFree.setText("下载全本");
                    btFree.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            StatisticsUtils.onEvent(BookCoverActivity.this,
                                    StatisticsEventID.BOOKCOVER_DOWNLOAD_ALLBOOK);
                            onStartDownBook();
                        }
                    });
                }
                break;
            case BT_BUYALLBOOK_SUCCES:
                if (this.orderdialog != null) {
                    this.orderdialog.dismiss();
                    if (buyBookInfo != null) {
                        String s =
                                TextUtils.isEmpty(buyBookInfo.getInfo()) ? "购买成功" : buyBookInfo
                                        .getInfo();
                        BottomToast.makeToast(this, s, R.drawable.common_icon_success).show();
                    }
                }
                loadDate(); // 通知加载数据
                break;
            case BT_BUY_BOOK_SUCCES:
                if (this.orderdialog != null) {
                    this.orderdialog.dismiss();
                    if (buyBookInfo != null) {
                        String s = (String) per;
                        s = TextUtils.isEmpty(s) ? "购买成功" : s;
                        BottomToast.makeToast(this, s, R.drawable.common_icon_success).show();
                    }
                }
                loadDate(); // 通知加载数据
                break;
            case BT_BUYALLBOOK_FAILURE:
                if (per != null) {
                    String buyStates = (String) per;
                    if (this.orderdialog != null) {
                        this.orderdialog.showBuyFailed(buyStates);
                    }
                }
                break;
            case BT_AUTHENTICATION_FAILED:
                if (per != null) {
                    this.orderdialog.dismiss();
                    String buyStates = (String) per;
                    showMsg(buyStates);
                    jumpLogin();
                }
                break;
            case BT_UNZIP_STOP: // TODO 解压失败 需要产品确认怎么显示按钮的状态

                updateButton(MyFavoritButtonScaleEnum._2to1);// 更新收藏按钮显示大小，显示比例2：1

                btPay.setVisibility(View.GONE);
                btPay.setClickable(false);
                btFree.setVisibility(View.VISIBLE);
                // DownloadInfo sqDownInfo =
                // DownLoadShuqiBook.getInstace().getDownBookState(
                // MyAccountManager.getInstance(this).getUserId(), bookId); // 获取下载信息
                // if (sqDownInfo != null) {
                // mShowDownLoadStates(sqDownInfo, btFree);
                // } else {
                btFree.setText("继续解压");
                btFree.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        StatisticsUtils.onEvent(BookCoverActivity.this,
                                StatisticsEventID.BOOKCOVER_DOWNLOAD_ALLBOOK);
                        onStartDownBook();
                    }
                });
                // }
                // showMsg("解压失败");
                break;
            case BT_STATE_UNZIP: // TODO 正在解压 需要产品确认怎么显示按钮的状态

                updateButton(MyFavoritButtonScaleEnum._2to1);// 更新收藏按钮显示大小，显示比例2：1

                btPay.setVisibility(View.GONE);
                btPay.setClickable(false);
                btFree.setVisibility(View.VISIBLE);
                btFree.setText("正在解压...");
                break;
            default:
                Log4an.e(LogTag, "errror state= " + state);
                break;
        }
    }

    /**
     * 购买成功或全本免费时的按钮状态显示
     * */
    private void mShowDownLoadStates(DownloadInfo downInfo, TextView btFree) {
        Log4an.e(LogTag, "读取数据库的状态：" + downInfo.getDownloadStatus());
        switch (downInfo.getDownloadStatus()) {
            case DownloadStatus.STATE_WAIT:
                btFree.setText("等待下载...");
                btFree.setClickable(false);
                break;
            case DownloadStatus.STATE_RUN:
                btFree.setText((int) (downInfo.getDownloadPercent()) + "% 下载中...");
                break;
            case DownloadStatus.STATE_STOP:
                btFree.setText((int) (downInfo.getDownloadPercent()) + "% 继续下载");
                btFree.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        StatisticsUtils.onEvent(BookCoverActivity.this,
                                StatisticsEventID.BOOKCOVER_GOON_DOWNLOAD);
                        onStartDownBook();
                    }
                });
                break;
            case DownloadStatus.STATE_UNZIP:
                btFree.setText("正在解压...");
                btFree.setClickable(false);
                break;
            case DownloadStatus.STATE_UNZIP_STOP:
                btFree.setText("继续解压");
                btFree.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        StatisticsUtils.onEvent(BookCoverActivity.this,
                                StatisticsEventID.BOOKCOVER_GOON_DOWNLOAD);
                        onStartDownBook();
                    }
                });
                break;
            case DownloadStatus.STATE_DONE:
                btFree.setText("阅读");
                btFree.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        onStartReadBook(true);
                    }
                });
                break;
        }
    }

    /** 购买弹出框 */
    private OrderDialog orderdialog = null;
    OrderInfo orderInfo = new OrderInfo();

    /** 全本购买书籍 */
    private void onStartBuyBook() {
        CheckUser.checkUserStateBeforeJump(this, new CheckUserListener() {
            @Override
            public void onPassed() {
                if (coverInfo.getPayMode() != Constant.PAYMODE_BOOK) {
                    return;
                }
                UserInfo userInfo = MyAccountManager.getInstance(BookCoverActivity.this);
                orderInfo = new OrderInfo();
                userInfo.setUserId(userInfo.getUserId());
                orderInfo.setBookId(coverInfo.getBookId());
                orderInfo.setBookName(coverInfo.getBookName());
                orderInfo.setPayMode(coverInfo.getPayMode());
                if (TextUtils.isEmpty(coverInfo.getDiscount())) {
                    orderInfo.setPrice(coverInfo.getOldPrice());
                } else {
                    orderInfo.setPrice(coverInfo.getPrice());
                }
                orderInfo.setOrderDetail("全本");
                Log4an.i(LogTag, "---" + orderInfo.toString());
                if (orderdialog == null) {
                    orderdialog = new OrderDialog(BookCoverActivity.this, orderInfo, false, true);
                }
                orderdialog.show();
                StatisticsUtils.onEvent(BookCoverActivity.this, StatisticsEventID.BOOKCOVER_ORDERDIALOG_SHOW);
            }
        });
    }


    /** 跳转到用户验证界面 */
    private void jumpLogin() {
        LoginActivity.openVerifyLoginForResultAndBack(this, RESULTCODE_JUMPLOGIN);
    }

    /** 开始阅读书籍 */
    private void onStartReadBook(boolean isFromReadbtn) {

        BookMarkInfo markInfo = null;
        markInfo =
                BookMarkInfoDao.getInstance().getBookMark(null, bookId,
                        MyAccountManager.getInstance(this).getUserId(),
                        BookMarkInfo.TYPE_NEW_PAY_BOOKMARK);
        if (markInfo == null) {
            markInfo = new BookMarkInfo();
            markInfo.setUserId(MyAccountManager.getInstance(this).getUserId());
            markInfo.setBookId(bookId);
            markInfo.setChapterId(coverInfo.getFirstChapterId());
            markInfo.setBookName(coverInfo.getBookName());
            markInfo.setBookType(BookMarkInfo.TYPE_NEW_PAY_BOOKMARK);
            markInfo.setBookCoverImgUrl(coverInfo.getImageUrl());
        }
        EnterBookContent.jumpToBookContentByBookMark(this, markInfo, -1);

        if (isFromReadbtn) {
            StatisticsUtils.onEvent(BookCoverActivity.this, StatisticsEventID.BOOKCOVER_READ);
        }
    }

    /** 开始阅读书籍 */
    private void onStartReadNewChapter() {
//        if (isUserAvailable()) {
//        } else {
//            jumpLogin();
//        }
        if (coverInfo != null && coverInfo.getNewChapter() != null
                && !TextUtils.isEmpty(coverInfo.getNewChapter().getChapterID())) {
            BookMarkInfo markInfo = new BookMarkInfo();
            markInfo.setUserId(MyAccountManager.getInstance(this).getUserId());
            markInfo.setBookId(bookId);
            markInfo.setChapterId(coverInfo.getNewChapter().getChapterID());
            markInfo.setBookName(coverInfo.getBookName());
            markInfo.setBookType(BookMarkInfo.TYPE_NEW_PAY_BOOKMARK);
            markInfo.setBookCoverImgUrl(coverInfo.getImageUrl());

            // markInfo.setChapterPayMode("" + coverInfo.getPayMode());

            Log4an.e("seekbar", "【markInfo】" + markInfo);
            EnterBookContent.jumpToBookContentByBookMark(this, markInfo, -1);
        } else {
            Log4an.e("seekbar", "最新章节：数据错误");
        }
    }

    /** 开始准备下载书籍 */
    private void onStartDownBook() {
        Log4an.e(LogTag, "开始准备下载...");
        if (!Util.isCanUseSdCard()) {
            showMsg(TxtDownLoadManager.NO_SDCARD);
            return;
        }
        if (!Util.isNetworkConnected(this)) {
            showMsg(getResources().getString(R.string.net_error_text));
            return;
        }
//        if (isUserAvailable()) {
//            
//        } else {
//            jumpLogin();
//        }

        boolean isShow = isShowNetWorkDialog();
        Message msg = new Message();
        msg.what = MSG_INIT_BT_STATE;
        if (!isShow) {
            DownLoadShuqiBook.getInstace().startDownBook(
                    MyAccountManager.getInstance(this).getUserId(), bookId,
                    coverInfo.getFirstChapterId(), new StartDownBookListener() {
                        @Override
                        public void onFinish(boolean isSuccess, String message) {
                            if (!isSuccess) {
                                showMsg(message);
                                initButtonState(coverInfo);
                            }
                        }
                    });
            msg.arg1 = BT_DOWN_WAITING;
            handler.sendMessage(msg);
        } else {
            showNetWorkDialog();
        }
    

    }

    /** 异步加载书旗图片 */
    private void asyncLoadImg(final ImageView iv) {
        if (iv != null && coverInfo != null && coverInfo.getImageUrl() != null
                && coverInfo.getImageUrl().startsWith("http")) {
            SqImageManager.getImageManager().displayImage(coverInfo.getImageUrl(), iv,
                    new SimpleAsyncTaskListener<Bitmap>() {
                        @Override
                        public void onAsyncTaskFailed(AsyncTaskFailReason failReason) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    findViewById(R.id.bookcover_iv_loading)
                                            .setVisibility(View.GONE);
                                }
                            });
                        }

                        @Override
                        public void onAsyncTaskComplete(Bitmap asyncTaskResult) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    findViewById(R.id.bookcover_iv_loading)
                                            .setVisibility(View.GONE);
                                }
                            });
                            
                            preLoadCatalogAndFirstContent();
                        }
                    }, SqImageManager.IMG_BIG_PICTURE);
        } else {
            findViewById(R.id.bookcover_iv_loading).setVisibility(View.GONE);
        }
    }

    private boolean isFirstShow = true;

    @Override
    protected void onResume() {
        if (isFirstShow) {
            isFirstShow = false;
        } else {
            updateBookData();
        }
        super.onResume();
    }

    /** 检查购买情况的数据 */
    private void updateBookData() {
        String userId = MyAccountManager.getInstance(getApplicationContext()).getUserId();
        BookInfo mInfo = BookInfoDao.getInstance().getBookInfo("", bookId, userId);
        if (coverInfo != null && mInfo != null
                && !String.valueOf(mInfo.getBookPayState()).equals(coverInfo.getPaid())) {
            Log4an.i(LogTag, "net:" + coverInfo.getPaid() + " local:" + mInfo.getBookPayState());
            showLoading(true);
            loadDate(); // 通知加载数据
        }
    }

    @Override
    protected void onStop() {

        super.onStop();
    }

    @Override
    protected void onDestroy() {
        controller.onDestroy();
        // FreeBookDownloadManager.getInstance().unRegisterDownStateListener(this);
        DownLoadShuqiBook.getInstace().unRegisterDownStateListener(this);
        super.onDestroy();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        BookCoverOtherBookInfo otherBook = coverInfo.getOtherList().get(position);
        if (otherBook.isHide()) {
            showMsg(getString(R.string.error_bookswitch_ishide));
            return;
        } else if (!otherBook.isCoverOpen()) {
            showMsg(getString(R.string.error_bookswitch_coverisclose));
            return;
        }
        BookCoverActivity.openBookCoverForAvoidCycle(this, otherBook.getBookId());
        StatisticsUtils.onEvent(this, StatisticsEventID.BOOKCOVER_OTHER_HADREAD);
    }


    // private DecimalFormat formater = new DecimalFormat("#0");

    /**
     * 下载状态监听方法
     * */
    @Override
    public void updateDownState(String uid, String bid, int state, float percent) {
        String loading = "";
        Message msg = new Message();
        msg.what = MSG_INIT_BT_STATE;
        switch (state) {
            case DownloadStatus.STATE_ERR_CONN:// 网络连接失败
            case DownloadStatus.STATE_ERR_DB:// 读取数据库失败
                msg.arg1 = BT_STATE_CONNECTERROR;
                break;
            case DownloadStatus.STATE_WAIT:
                msg.arg1 = BT_DOWN_WAITING;
                break;
            case DownloadStatus.STATE_RUN:
                msg.arg1 = BT_DOWNING;
                loading = "" + (int) percent;
                break;
            case DownloadStatus.STATE_STOP:
                msg.arg1 = BT_DOWN_ERROR;
                loading = "" + (int) percent;
                break;
            case DownloadStatus.STATE_UNZIP:
                loading = "" + (int) percent;
                msg.arg1 = BT_STATE_UNZIP;
                break;
            case DownloadStatus.STATE_UNZIP_STOP:
                loading = "" + (int) percent;
                msg.arg1 = BT_UNZIP_STOP;
                break;
            case DownloadStatus.STATE_DONE:
                msg.arg1 = BT_DOWANING_CANREAD;
                // showMsg("下载成功");
                break;
        }
        Log4an.e(LogTag, "下载状态监听事件state:" + state + "；进度：" + percent + ";处理后的进度：" + loading);
        msg.obj = loading;
        if (bid.equals(coverInfo.getBookId())
                && uid.equals(MyAccountManager.getInstance(this).getUserId())) {
            handler.sendMessage(msg);
        } else {
            return;
        }
    }

    /** 网络选择弹出框 */
    private Dialog mNetworkDialog;

    /** 显示网络选择框 */
    private void showNetWorkDialog() {
        if (mNetworkDialog == null) {
            View view = getLayoutInflater().inflate(R.layout.view_dialog_network, null);
            view.findViewById(R.id.dialog_cancel_tv).setOnClickListener(this);
            view.findViewById(R.id.dialog_confirm_tv).setOnClickListener(this);
            mNetworkDialog = new Dialog(this, R.style.net_dialog);
            LayoutParams params =
                    new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            mNetworkDialog.addContentView(view, params);
            mNetworkDialog.setCanceledOnTouchOutside(true);
        }
        mNetworkDialog.show();
    }

    /** 隐藏网络选择框 */
    private void hideNetWorkDialog() {
        if (mNetworkDialog != null && mNetworkDialog.isShowing()) {
            mNetworkDialog.dismiss();
        }
    }

    /** 是否显示网络选择框 */
    private boolean isShowNetWorkDialog() {
        boolean isNoWifi = NetNotify.getInstance().isNeedNotifyNoWifi(NetNotify.DOWNLOAD_BOOK_READ);
        return isNoWifi;
    }

    /** 底部跳转绑定弹出框 */
    private BottomDialog dialogBinding = null;
    private String chapterInfo;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log4an.i(LogTag, "requestCode=" + requestCode + ",resultCode=" + resultCode);
        UserInfo userInfo = MyAccountManager.getInstance(this, true);
        if (requestCode == RESULTCODE_JUMPLOGIN) {
            if (resultCode == Activity.RESULT_OK) {
                showLoading(true);
                loadDate(); // 通知加载数据
            }
        } else if (requestCode == Constant.ORDER_REQUESTCOD) {//
            if (resultCode == Activity.RESULT_OK && !MyAccountManager.isVipUser(userInfo)
                    && !MyAccountManager.isGuestUser(userInfo)) {
                showBottomDialog();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /** 显示底部账户绑定弹出框 */
    private void showBottomDialog() {
        if (this.dialogBinding == null) {
            View viewv = View.inflate(this, R.layout.account_safety_tips, null);
            this.dialogBinding = new BottomDialog(this, viewv);
            this.initDialogBindingDialog(viewv);
            viewv.setOnClickListener(this);
        }
        this.dialogBinding.show();
        StatisticsUtils.onEvent(BookCoverActivity.this,
                StatisticsEventID.AFTERPAYFINISH_HINT_SHOWBIND);
    }

    /**
     * 弹出绑定账户提示事件响应
     */
    private void initDialogBindingDialog(View view) {
        view.findViewById(R.id.binding_account).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                AccountBindActivity.show(BookCoverActivity.this);
                if (dialogBinding != null) {
                    dialogBinding.dismiss();
                }
                StatisticsUtils.onEvent(BookCoverActivity.this,
                        StatisticsEventID.AFTERPAYFINISH_HINT_CLICKBIND);
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if("open".equals(getIntent().getStringExtra("push_book"))){
                MainActivityGroup.showFromBookShelf(this, 1, true);
            }
            // return false;
            ActivityManager.getInstance().finishActivity(this);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 打开书籍封面页
     * 
     * @param activity
     * @param bookId
     */
    public static void openBookCover(final Activity activity, final String bookId) {
        openBookCover(activity, bookId, false);
    }

    /**
     * 打开书籍封面页
     * 
     * @param activity
     * @param bookId
     */
    public static void openBookCoverClearTop(final Activity activity, final String bookId) {
        openBookCover(activity, bookId, true);
    }

    /**
     * 打开书籍封面页
     * 
     * @param activity
     * @param bookId
     * @param isClearTop
     */
    private static void openBookCover(final Activity activity, final String bookId,
            final boolean isClearTop) {
        if(TextUtils.isEmpty(bookId) || "null".equals(bookId)){
            ToastUtil.showMessage("书籍ID为空");
            return;
        }
        Intent intent = new Intent(activity, BookCoverActivity.class);
        intent.putExtra(INTENT_NAME_BOOKID, bookId);
        if (isClearTop) {
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        }
        ActivityManager.getInstance().startNextActivity(intent, activity);
    }

    /**
     * 打开书籍封面页[避免循环]
     * 
     * @param activity
     * @param bookId
     * @param isClearTop
     */
    public static void openBookCoverForAvoidCycle(final Activity activity, final String bookId) {
        Intent intent = new Intent(activity, BookCoverActivity.class);
        intent.putExtra(INTENT_NAME_BOOKID, bookId);
        ActivityManager.getInstance().startActivity(intent, activity);
    }


    /**
     * 添加收藏
     * 
     * @param view
     */
    public void addMyfavorit(View view) {
        if (!Util.isNetworkConnected(this)) {// 没网
            handler.sendEmptyMessage(MSG_MYFAVORIT_DATA_ERROR);
            return;
        }
        
        CheckUser.checkUserStateBeforeJump(this, new CheckUserListener() {
            @Override
            public void onPassed() {
                showDialog("添加收藏中，请稍候...");
                myFavoritcontroller.handle(0, bookId, ActionEnum.add);
                action = 1;
                StatisticsUtils.onEvent(BookCoverActivity.this, StatisticsEventID.BOOKCOVER_COLLECTION_ADD);
            }
        });
    }

    /**
     * 取消收藏
     * 
     * @param view
     */
    public void removeMyfavorit(View view) {
        if (!Util.isNetworkConnected(this)) {// 没网
            handler.sendEmptyMessage(MSG_MYFAVORIT_DATA_ERROR);
            return;
        }
        
        CheckUser.checkUserStateBeforeJump(this, new CheckUserListener() {
            @Override
            public void onPassed() {
                showDialog("取消收藏中，请稍候...");
                myFavoritcontroller.handle(0, bookId, ActionEnum.remove);
                action = 2;
                StatisticsUtils.onEvent(BookCoverActivity.this, StatisticsEventID.BOOKCOVER_COLLECTION_DELETE);
            }
        });
    }

    private void showDialog(String msg) {
        if (myFavoritRemoveTv != null)
            myFavoritRemoveTv.setClickable(false);

        if (toastDialog == null) {
            toastDialog = new ToastDialog(this);
            toastDialog.setOnCancelListener(new OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {}
            });
        }
        toastDialog.setDissmisOnClickOutSide(false);
        toastDialog.loading(msg);

    }

    private void dismissDialog() {
        if (myFavoritRemoveTv != null)
            myFavoritRemoveTv.setClickable(true);

        if (toastDialog != null) {
            toastDialog.dismiss();
        }


    }

    // 显示收藏满的dialog
    private void showBottomFullDialog() {

        String title = "添加收藏提示";
        String content = "您的收藏夹已满，添加新书需要更多空间。";

        if (fullDialog != null && !fullDialog.isShowing()) {
            fullDialog.dismiss();
        }

        fullDialog =
                DialogUtils.showDialogConfirmBottom(this, title, content, "管理收藏", "取消",
                        new OnClickListener() {

                            @Override
                            public void onClick(View v) {

                                DialogUtils.dismissDialog(fullDialog);
                                Intent intent =
                                        new Intent(BookCoverActivity.this, MyFavoritActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                ActivityManager.getInstance().startNextActivity(intent,
                                        BookCoverActivity.this);

                            }
                        }, new OnClickListener() {

                            @Override
                            public void onClick(View v) {

                                DialogUtils.dismissDialog(fullDialog);

                            }
                        });


    }

    /**
     * 更新按钮显示比例
     * 
     * @param weight 收藏按钮显示比重,值越大显示比例超大，可选值 1f或0.5f
     */
    private void updateButton(MyFavoritButtonScaleEnum scale) {

        // 根据按钮数量,布局按钮显示比例大小
        if (myFavoritAddTv != null && myFavoritRemoveTv != null) {

            LinearLayout.LayoutParams myFavoritAddParams =
                    (LinearLayout.LayoutParams) myFavoritAddTv.getLayoutParams();
            LinearLayout.LayoutParams myFavoritRemoveParams =
                    (LinearLayout.LayoutParams) myFavoritRemoveTv.getLayoutParams();
            
            if(scale.equals(MyFavoritButtonScaleEnum._1to1)){
                myFavoritAddParams.weight = 1.0f;
                myFavoritRemoveParams.weight = 1.0f;
            }else if(scale.equals(MyFavoritButtonScaleEnum._2to1)){
                myFavoritAddParams.weight = 0.5f;
                myFavoritRemoveParams.weight = 0.5f;
            }

            myFavoritAddTv.setLayoutParams(myFavoritAddParams);
            myFavoritRemoveTv.setLayoutParams(myFavoritRemoveParams);
        }

    }
}
